package com.apache.flow.core.dao;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.SQLException;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import org.jbpm.api.ProcessEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.apache.core.orm.hibernate.ApacheBaseDao;
import com.apache.flow.core.entity.FlowInitEntity;

@SuppressWarnings("all")
@Repository
public class FlowInitDao extends ApacheBaseDao {
	@Autowired
	private ProcessEngine processEngine;

	/**
	 * 
	 * @param is 输入流
	 * @param id 流程发布Id
	 * @return
	 * <p>@description 根据流程发布Id获取工作流中存放的lob大数据对象
	 * <p>@version 1.0
	 * <p>@author lvcai
	 * <p>@update 2013-7-29 下午04:02:42
	 */
	public String updateJpdl(InputStream is, int id) {
		Reader r = null;
		String s = null;

		try {
			r = new InputStreamReader(is);
			int b = 0;
			StringBuffer sb = new StringBuffer();
			while ((b = r.read()) != -1) {
				char c = (char) b;
				s = String.valueOf(c);
				sb.append(s);

			}
			SessionFactory sessionFactory = processEngine.get(SessionFactory.class);
			Session session = sessionFactory.openSession();
			List<FlowInitEntity> list = session.createSQLQuery("select * from jbpm4_lob where deployment_=? ")
					.addEntity(FlowInitEntity.class).setParameter(0, id).list();
			FlowInitEntity lob = new FlowInitEntity();

			Transaction tx = session.beginTransaction();
			session.update(lob);
			tx.commit();
			session.close();

		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * 
	 * @param deployment  流程发布Id
	 * @param name  文件名
	 * @param blob_value  blob值
	 * @return
	 * <p>@description 更新流程定义文件
	 * <p>@version 1.0
	 * <p>@author lvcai
	 * <p>@update 2013-7-29 下午04:06:08
	 */
	public String update(String deployment, String name, String blob_value) {
		try {
			SessionFactory sessionFactory = processEngine.get(SessionFactory.class);
			Session session = sessionFactory.openSession();
			Criteria criteria = session.createCriteria(FlowInitEntity.class);
			criteria.add(Restrictions.eq("deployment", new BigDecimal(deployment)));
			List lobList = criteria.list();
			int count = lobList.size();
			for (int i = 0; i < count; i++) {
				FlowInitEntity lob = (FlowInitEntity) lobList.get(i);
				String resourceName = clob2String(lob.getName());
				if (resourceName.endsWith(".xml")) {
					Blob blob = string2Blob(blob_value);
					Transaction tx = session.beginTransaction();
					lob.setBlobValue(blob);
					session.save(lob);
					tx.commit();
					break;
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 
	 * @param id
	 * <p>@description 根据组件Id获取初始化实体
	 * <p>@version 1.0
	 * <p>@author lvcai
	 * <p>@update 2013-7-29 下午04:09:09
	 */
	public void getFlow(String id) {
		this.getSession().load(FlowInitEntity.class, id);
	}

	/**
	 * 
	 * @param fie
	 * <p>@description 修改flowInit实体方法
	 * <p>@version 1.0
	 * <p>@author lvcai
	 * <p>@update 2013-7-29 下午04:09:41
	 */
	public void updateTestBlob(FlowInitEntity fie) {
		this.getSession().update(fie);
	}

	/**
	 * 
	 * @param idea 字符串
	 * @return
	 * <p>@description 将String对象转化为blob类型对象
	 * <p>@version 1.0
	 * <p>@author lvcai
	 * <p>@update 2013-7-29 下午04:10:57
	 */
	public Blob string2Blob(String idea) {
		byte[] content = null;
		if (idea == null || "".equals(idea)) {
			return null;
		}

		try {
			content = idea.getBytes("UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		Blob blob = Hibernate.createBlob(content);
		return blob;
	}

	/**
	 * 
	 * @param blob blob对象
	 * @return
	 * <p>@description 将blob转化为字符串
	 * <p>@version 1.0
	 * <p>@author lvcai
	 * <p>@update 2013-7-29 下午04:11:34
	 */
	public String blob2String(Blob blob) {
		String contentStr = null;
		InputStream input = null;
		ByteArrayOutputStream baos = null;
		try {
			input = blob.getBinaryStream();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		try {
			baos = new ByteArrayOutputStream();
			int i = -1;
			while ((i = input.read()) != -1) {
				baos.write(i);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			contentStr = new String(baos.toByteArray(), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return contentStr;
	}

	/**
	 * 
	 * @param idea 字符串信息
	 * @return
	 * <p>@description 将String转化为clob
	 * <p>@version 1.0
	 * <p>@author lvcai
	 * <p>@update 2013-7-29 下午04:13:20
	 */
	public Clob string2Clob(String idea) {
		byte[] content = null;
		if (idea == null || "".equals(idea)) {
			return null;
		}

		try {
			content = idea.getBytes("UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		Clob clob = Hibernate.createClob(idea);
		return clob;
	}

	/**
	 * 
	 * @param clob
	 * @return
	 * <p>@description 方法描述
	 * <p>@version 1.0
	 * <p>@author lvcai
	 * <p>@update 2013-7-29 下午04:14:13
	 */
	public String clob2String(Clob clob) {
		String contentStr = null;
		InputStream input = null;
		ByteArrayOutputStream baos = null;
		try {
			input = clob.getAsciiStream();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		try {
			baos = new ByteArrayOutputStream();
			int i = -1;
			while ((i = input.read()) != -1) {
				baos.write(i);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			contentStr = new String(baos.toByteArray(), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return contentStr;
	}
}
